import os
from datetime import datetime
import unittest
from common.BeautifulReport import BeautifulReport

DIR = os.path.dirname(os.path.abspath(__file__))
ENVIRON = 'Offline'  # 'Online' -> 线上环境， 'Offline' -> 测试环境


def iter_test_cases(suite):
    """
    递归遍历 TestSuite，返回所有 TestCase 实例
    """
    for item in suite:
        if isinstance(item, unittest.TestSuite):
            yield from iter_test_cases(item)
        else:
            yield item


if __name__ == '__main__':
    # 设置报告目录
    report_dir = os.path.join(DIR, 'report')  #
    os.makedirs(report_dir, exist_ok=True)

    # 生成带时间戳的报告名
    timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
    report_filename = f"report_v1_{timestamp}.html"

    # 指定加载顺序
    discover_order = [
        ('./testCase/hiflyApiV1/voice', 'TestCaseV1CreateCosyVoices.py'),
        ('./testCase/hiflyApiV1/voice', 'TestCaseV1CreateMegaVoices.py'),
        ('./testCase/hiflyApiV1/voice', 'TestCaseV1VoicesList.py'),
        ('./testCase/hiflyApiV1/account', 'TestCaseV1AccountCredit.py'),
        ('./testCase/hiflyApiV1/create_v1_task', 'TestCaseV1CreateTask.py'),
        ('./testCase/hiflyApiV1/create_v1_task', 'TestCaseV1CheckCreateTask.py')
    ]

    all_suite = unittest.TestSuite()
    added_set = set()

    for path, pattern in discover_order:
        suite = unittest.TestLoader().discover(path, pattern=pattern)
        for test_case in iter_test_cases(suite):
            identifier = f"{test_case.__class__.__name__}.{test_case._testMethodName}"
            if identifier not in added_set:
                added_set.add(identifier)
                all_suite.addTest(test_case)

    # 生成报告：飞书专用（带时间戳）
    result = BeautifulReport(all_suite)
    result.report(filename=report_filename, description='V1接口测试报告', report_dir=report_dir)

    # 再生成一份固定名为 index.html 的报告（Jenkins HTML Publisher 使用）
    result2 = BeautifulReport(all_suite)
    result2.report(filename='index.html', description='V1接口测试报告', report_dir=report_dir)



